package asyncudp;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;
import io.netty.util.CharsetUtil;

public class TheMomentServerHandler extends SimpleChannelInboundHandler<DatagramPacket> {

    // Quotes from Mohandas K. Gandhi:
    private static final String quote = "First they ignore you, then they laugh at you, then they fight you, then you win.";

    @Override
    public void channelRead0(ChannelHandlerContext ctx, DatagramPacket packet) throws Exception {
        String mes = packet.content().toString(CharsetUtil.UTF_8);

        // <Client> --packet([BEAT])--> <Server>
        if (mes.startsWith("[BEAT]")) {

            System.out.println("[LOG]: " + packet.sender() + " ... keep alive ...");

            // <Server> --packet([SERVER])--> <Client>
            ctx.write(new DatagramPacket(
                Unpooled.copiedBuffer("[BEAT]", CharsetUtil.UTF_8),
                packet.sender()
            ));

        } else if (mes.startsWith("[CLIENT]")) {

            System.out.println(mes);

            ctx.write(new DatagramPacket(
                Unpooled.copiedBuffer("[ACK]" + quote, CharsetUtil.UTF_8),
                packet.sender()
            ));
        }
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) {

        // after client read the response
        System.out.println("[LOG]: channelReadComplete. ctx.flush()");
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        // We don't close the channel because we can keep serving requests.
    }
}